//
//  RegisterViewController.m
//  NOAHWM
//
//  Created by Ryan on 13-5-14.
//  Copyright (c) 2013年 Ryan. All rights reserved.
//

#import "RegisterViewController.h"
#import "NSString+MobileNum.h"
#import "ConfirmViewController.h"
#import "NYMemberCenterDataManager.h"
#import "MyCLController.h"
#import "NSString+SBJSON.h"
#import "CitiesSelectViewController.h"

static NSString *const CurrentADLocationCityKey     = @"CurrentADLocationCity";

@interface RegisterViewController ()

@end

@implementation RegisterViewController

@synthesize nameField,phoneField,nextButton;
@synthesize googleLNDownloader;
@synthesize addressLabel;
@synthesize locationCity;
@synthesize citys;
@synthesize indexCityDict;

#pragma mark - Private methods
- (NSString *)checkFieldValid
{
    //姓名长度1-20
    //手机号长度11-11 手机号验证
    if(nameField.text.length < 1)
        return [NSString stringWithFormat:[kRegisterPromptDict objectForKey:@"F000001E"],@"姓名"];
    else if(nameField.text.length > 20)
        return [NSString stringWithFormat:[kRegisterPromptDict objectForKey:@"F000002E"],@"姓名"];
    else if(phoneField.text.length < 1)
        return [NSString stringWithFormat:[kRegisterPromptDict objectForKey:@"F000001E"],@"手机号"];
    else if(phoneField.text.length > 11)
        return [NSString stringWithFormat:[kRegisterPromptDict objectForKey:@"F000002E"],@"手机号"];
    else if(![NSString isMobileNumber:phoneField.text])
        return [NSString stringWithFormat:[kRegisterPromptDict objectForKey:@"F000003E"],@"手机号"];
    return nil;
}

- (void)enableNextButton
{
    self.nextButton.enabled = YES;
}

#pragma mark -
- (void)getLocationCoord
{
    if (!locationController) {
        locationController = [[MyCLController alloc]init];
        locationController.delegate = self;
    }
    [locationController startLocate];
}

#pragma mark - IBActions
- (IBAction)nextButtonClicked:(id)sender
{
    [self.nameField resignFirstResponder];
    [self.phoneField resignFirstResponder];
    NSString *validString = [self checkFieldValid];
    if(validString)
    {
        [[RYHUDManager sharedManager] showWithMessage:validString customView:nil hideDelay:2.f];
    }
    else
    {
        //调用server 发送密码短信手机接口，保存本地输入的用户名手机号到MemberCenter
        [NYMemberCenterDataManager sharedManager].loginMember.userName = self.nameField.text;
        [NYMemberCenterDataManager sharedManager].loginMember.phoneNum = self.phoneField.text;
        
        NSString *url = [NSString stringWithFormat:@"%@%@",kServerAddress,[NSString stringWithFormat:kDynamicPasswordUrl,@"jsonp",phoneField.text,@"1"]];
        url = [url stringByAppendingString:@"app000021"];
        url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [[RYDownloaderManager sharedManager] requestDataByGetWithURLString:url delegate:[NYMemberCenterDataManager sharedManager] purpose:kDynamicPasswordDownloaderKey];
        
        [[RYHUDManager sharedManager] startedNetWorkActivityWithText:@"密码获取中..."];
    }
}

- (IBAction)citiesSelectPressed:(id)sender {
    CitiesSelectViewController *csvc = [[CitiesSelectViewController alloc]init];
    [csvc.nameIndexDict addEntriesFromDictionary:self.indexCityDict];
    csvc.gpsLocation = self.locationCity;
    csvc.selectedLocation = self.addressLabel.text;
    [self.navigationController pushViewController:csvc animated:YES];
    //[csvc.citiesBlanch arrayByAddingObjectsFromArray:self.citys];
    //csvc.gpsLocation = self.locationCity;
    [csvc release];
}

#pragma mark - Notification methods
- (void)dynamicPasswordResponseSucceedWithNotification:(NSNotification *)notification
{
    self.nextButton.enabled = NO;
    [self performSelector:@selector(enableNextButton) withObject:nil afterDelay:30.f];
    [[RYHUDManager sharedManager] showWithMessage:notification.object customView:nil hideDelay:2.f];
    ConfirmViewController *cvc = [[ConfirmViewController alloc] init];
    cvc.myBlanch = [NSString stringWithString:self.addressLabel.text];
    [self.navigationController pushViewController:cvc animated:YES];
    [cvc release];
}

- (void)dynamicPasswordResponseErrorWithNotification:(NSNotification *)notification
{
    [[RYHUDManager sharedManager] showWithMessage:notification.object customView:nil hideDelay:2.f];
}

- (void)changeBanchCityWithNotification:(NSNotification *)notification
{
    self.addressLabel.text = [NSString stringWithFormat:@"%@",notification.object];
}
#pragma mark - BaseViewController methods
- (void)leftItemTapped
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UIViewController methods
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dynamicPasswordResponseSucceedWithNotification:) name:kDynamicPasswordResponseSucceedNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dynamicPasswordResponseErrorWithNotification:) name:kDynamicPasswordResponseErrorNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeBanchCityWithNotification:) name:kSelectedBlanchCityNotification object:nil];
    
    [self setNaviTitle: @"快速注册"];
    [self setLeftNaviItemWithTitle:@"返回" imageName:@"Icon_Back"];
    [self setRightNaviItemWithTitle:nil imageName:nil];
    [self addSwipePopGesture];
    //[self setRightNaviItemWithTitle:@"保存" imageName:nil];
    [self getLocationCoord];
    self.indexCityDict = [NSMutableDictionary dictionary];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.isViewLoaded && !self.view.window)
    {
        [[NSNotificationCenter defaultCenter] removeObserver:self];
        [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
        self.view = nil;
        self.nameField = nil;
        self.phoneField = nil;
        self.nextButton = nil;
        self.addressLabel = nil;
        self.googleLNDownloader = nil;
        self.locationCity = nil;
        self.citys = nil;
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:nil purpose:nil];
    self.nameField = nil;
    self.phoneField = nil;
    self.nextButton = nil;
    self.addressLabel = nil;
    self.googleLNDownloader = nil;
    self.locationCity = nil;
    self.citys = nil;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:nil purpose:nil];
    
    [locationController stopLocate];
    [locationController release];
    locationController = nil;
    
    [nameField release];
    [phoneField release];
    [nextButton release];
    [addressLabel release];
    [googleLNDownloader cancelLocationNameDownload];
    [googleLNDownloader release];
    googleLNDownloader = nil;
    [locationCity release];
    [citys release];
    [super dealloc];
}

#pragma mark - UITextFieldDelegate methods
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if(textField == self.nameField)
    {
        [self.nameField resignFirstResponder];
        [self.phoneField becomeFirstResponder];
    }
    else if(textField == self.phoneField)
    {
        [self.phoneField resignFirstResponder];
        [self nextButtonClicked:nil];
    }
    return YES;
}

#pragma mark - MyCLController Delegate
- (void)locationUpdate:(CLLocation *)location
{
    [locationController stopLocate];
    //NSLog(@"location = %@", location);
    locationCoord = location.coordinate;
    [self performSelectorOnMainThread:@selector(getLocationName) withObject:nil waitUntilDone:NO];
}

- (void)locationError:(NSError *)error
{
    [locationController stopLocate];
    //NSLog(@"location = %@", location);
    locationCoord = CLLocationCoordinate2DMake(0, 0);
    [self performSelectorOnMainThread:@selector(getLocationName) withObject:nil waitUntilDone:NO];
}

- (void)getLocationName
{
    [self.googleLNDownloader cancelLocationNameDownload];
    googleLNDownloader = [[GoogleLocationNameDownloader alloc]init];
    self.googleLNDownloader.delegate = self;
    [googleLNDownloader startLocationNameDownload:locationCoord];
}

#pragma mark - GoogleLocationNameDownloaderDelegate
- (void)LocationNameDidLoad:(NSString *)locationName
{
    //self.addressLabel.text = locationName;
    self.locationCity = locationName;
    
    //get the list of blanch
    NSString *url = [NSString stringWithFormat:@"%@%@",kServerAddress,[NSString stringWithFormat:kFindDictBykindTypeUrl,@"jsonp",kBlanchTypeKind]];
    url = [url stringByAppendingString:@"app000057"];
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[RYDownloaderManager sharedManager] requestDataByGetWithURLString:url delegate:self purpose:nil];
    
    //[[RYHUDManager sharedManager] startedNetWorkActivityWithText:@"列表获取中"];

}


#pragma mark - RYDownloaderDelegate methods
- (void)downloader:(RYDownloader*)downloader completeWithNSData:(NSData*)data
{
    NSString *str = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    //去掉被包的jsonp字串
    if(str.length > 7)
        str = [str substringWithRange:NSMakeRange(6, str.length-7)];
    NSDictionary *dict = [str JSONValue];
    if([[dict objectForKey:@"result"] isEqualToString:@"1"])
    {
        NSArray *resultList = [dict objectForKey:@"resultlist"];
        
        NSMutableArray *existingArray;
        int flag = 0;
        for (NSDictionary *element in  resultList) {
            NSString *cityName = [element objectForKey:@"csDesc"];
            NSString *indexName = [element objectForKey:@"remark"];
            if (nil!=(existingArray = [self.indexCityDict valueForKey:indexName])) {
                [existingArray addObject:cityName];
            }
            else{
                NSMutableArray *tempArray = [NSMutableArray array];
                [self.indexCityDict setObject:tempArray forKey:indexName];
                [tempArray addObject:cityName];
            }
            
            NSString *location = [NSString stringWithFormat:@"%@市",cityName];
            if ([location isEqualToString: self.locationCity]) {
                self.addressLabel.text = cityName;
                flag = 1;
            }
        }
        if (flag == 0) {
            
            NSArray *allkey = [[self.indexCityDict allKeys] sortedArrayUsingComparator:^NSComparisonResult(NSString *key1, NSString *key2){
                return [key1 compare:key2];
            }];
            
            NSString *name = [[self.indexCityDict objectForKey:allkey[0]] objectAtIndex:0];
            self.addressLabel.text = name;
        }
        [self presortElementInitialLetterIndexes];
    }
    

#if 0
    NSString *str = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    //去掉被包的jsonp字串
    if(str.length > 7)
        str = [str substringWithRange:NSMakeRange(6, str.length-7)];
    NSDictionary *dict = [str JSONValue];
    if([[dict objectForKey:@"result"] isEqualToString:@"1"])
    {
        NSArray *resultList = [dict objectForKey:@"resultlist"];
        int count = resultList.count;
        self.citys = [NSMutableArray arrayWithCapacity:count];
        int flag = 0;
        for (int i=0; i<count; i++) {
            [self.citys addObject:[resultList[i] objectForKey:@"csDesc"]];
            NSString *location = [NSString stringWithFormat:@"%@市", [resultList[i] objectForKey:@"csDesc"]];
            //NSLog(@"%@,%@",location,locationCity);
            if ([location isEqualToString: self.locationCity]) {
                self.addressLabel.text = [resultList[i] objectForKey:@"csDesc"];
                flag = 1;
            }
        }
        if (flag == 0) {
            self.addressLabel.text = [resultList[0] objectForKey:@"csDesc"];
        }
    }
#endif
}

- (void)downloader:(RYDownloader*)downloader didFinishWithError:(NSString*)message
{
    [[RYHUDManager sharedManager] showWithMessage:kNetWorkErrorString customView:nil hideDelay:2.f];
}


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

// presort the name index arrays so the elements are in the correct order
- (void)presortElementInitialLetterIndexes {
	self.citys = [[self.indexCityDict allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
	//for (NSString *eachNameIndex in self.nameIndexArray) {
    //[self presortElementNamesForInitialLetter:eachNameIndex];
	//}
}
@end
